﻿using nhCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace nhCore.Modbus
{
    internal class YunHistoryDataAnalyzer : YunAnalyzer
    {
        public YunHistoryDataAnalyzer(byte address) : base(address)
        {
        }

        public override object Analysis(object o)
        {
            Http.BootHistoryData bootHistoryData = (Http.BootHistoryData)o;

            Dictionary<DateTime, Dictionary<int, double?>> dicCache = new Dictionary<DateTime, Dictionary<int, double?>>();
            foreach (Http.OpenApiHistoryData field in bootHistoryData.Data)
            {

                foreach (KeyValuePair<DateTime, double?> timeValue in field.Values)
                {
                    if (!dicCache.ContainsKey(timeValue.Key))
                    {
                        dicCache.Add(timeValue.Key, new Dictionary<int, double?>());
                    }

                    if (!dicCache[timeValue.Key].ContainsKey(field.Index))
                    {
                        dicCache[timeValue.Key].Add(field.Index, null);
                    }
                    dicCache[timeValue.Key][field.Index] = timeValue.Value;
                }
            }

            List<Weathers> listWeathers = new List<Weathers>();
            foreach (KeyValuePair<DateTime, Dictionary<int, double?>> timeDic in dicCache.Reverse())
            {
                Weathers weathers = new Weathers
                {
                    Address = Address
                };

                foreach (Decoder d in Decoders)
                {
                    Weather w = new Weather
                    {
                        Config = d.Config,
                    };

                    if (d is WeatherDecoder)
                    {
                        foreach (KeyValuePair<int, double?> indexValue in timeDic.Value)
                        {
                            if (w.Config.Index == indexValue.Key)
                            {
                                w.Value = indexValue.Value;
                            }
                        }
                    }
                    else if (d is TimeDecoder)
                    {
                        w.Value = timeDic.Key.Ticks;
                    }
                    //w.StrValue = w.Value.HasValue ? d.Convert(w.Value.Value) : "-";
                    weathers.AddValue(w.Config.Index, w);//时间为index为-1，传感器数据也可能为0
                }
                listWeathers.Add(weathers);
            }

            return listWeathers;
        }
    }
}
